package com.ruoyi.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/ai")
@CrossOrigin(origins = "*")
public class HomeworkGradingController {
    
    @Value("${spring.ai.openai.api-key}")
    private String apiKey;
    
    @Value("${spring.ai.openai.base-url}")
    private String baseUrl;
    
    @Value("${spring.ai.openai.chat.options.model}")
    private String model;
    
    private final ObjectMapper objectMapper = new ObjectMapper();
    
    @PostMapping("/grade")
    public Map<String, Object> gradeHomework(@RequestBody Map<String, Object> request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String ocrText = (String) request.get("ocrText");
            String subject = (String) request.get("subject");
            String gradingCriteria = (String) request.get("gradingCriteria");
            
            if (ocrText == null || ocrText.trim().isEmpty()) {
                response.put("success", false);
                response.put("error", "OCR文本不能为空");
                return response;
            }
            
            // 构建批改提示词
            String prompt = buildGradingPrompt(ocrText, subject, gradingCriteria);
            
            // 调用AI模型进行批改
            String aiResponse = callDeepSeek(prompt);
            
            // 添加调试日志
            System.out.println("=== AI原始响应 ===");
            System.out.println(aiResponse);
            System.out.println("=== AI响应结束 ===");
            
            // 解析AI响应并构建返回结果
            Map<String, Object> gradingResult = parseAIResponse(aiResponse);
            
            response.put("success", true);
            response.put("data", gradingResult);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("error", "批改过程中发生错误: " + e.getMessage());
            e.printStackTrace();
        }
        
        return response;
    }
    
    @GetMapping("/generate")
    public String generateResponse(@RequestParam(value = "message", defaultValue = "hello") String message) {
        try {
            String response = callDeepSeek(message);
            System.out.println("AI Response: " + response);
            return response;
        } catch (Exception e) {
            e.printStackTrace();
            return "AI服务调用失败: " + e.getMessage();
        }
    }
    
    private String callDeepSeek(String message) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(baseUrl + "/chat/completions");
        
        // 设置请求头
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setHeader("Authorization", "Bearer " + apiKey);
        
        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", model);
        requestBody.put("max_tokens", 1000);
        requestBody.put("temperature", 0.1);
        
        Map<String, String> messageObj = new HashMap<>();
        messageObj.put("role", "user");
        messageObj.put("content", message);
        requestBody.put("messages", new Object[]{messageObj});
        
        String jsonBody = objectMapper.writeValueAsString(requestBody);
        httpPost.setEntity(new StringEntity(jsonBody, "UTF-8"));
        
        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            HttpEntity entity = response.getEntity();
            String responseBody = EntityUtils.toString(entity);
            
            // 解析响应
            JsonNode jsonNode = objectMapper.readTree(responseBody);
            if (jsonNode.has("choices") && jsonNode.get("choices").size() > 0) {
                return jsonNode.get("choices").get(0).get("message").get("content").asText();
            } else if (jsonNode.has("error")) {
                throw new RuntimeException("DeepSeek API错误: " + jsonNode.get("error").get("message").asText());
            } else {
                throw new RuntimeException("未知的API响应格式: " + responseBody);
            }
        } finally {
            httpClient.close();
        }
    }
    
    private String buildGradingPrompt(String ocrText, String subject, String gradingCriteria) {
        StringBuilder prompt = new StringBuilder();
        prompt.append("请作为一名专业的").append(subject != null ? subject : "").append("老师，对以下学生作业进行批改：\n\n");
        prompt.append("学生作业内容：\n").append(ocrText).append("\n\n");
        
        if (gradingCriteria != null && !gradingCriteria.trim().isEmpty()) {
            prompt.append("批改标准：\n").append(gradingCriteria).append("\n\n");
        }
        
        prompt.append("请按照以下格式进行批改：\n");
        prompt.append("得分：[请给出0-100的具体分数]/100\n");
        prompt.append("1. 总体评价：[对作业的整体评价]\n");
        prompt.append("2. 优点：[列出作业的优点，每个优点一行，用-开头]\n");
        prompt.append("3. 不足之处：[指出需要改进的地方，每个不足一行，用-开头]\n");
        prompt.append("4. 改进建议：[提供具体的改进建议，每个建议一行，用-开头]\n");
        prompt.append("5. 鼓励话语：[给学生一些鼓励的话]\n");
        prompt.append("6. 错题分析：[如果有错题，请按以下格式列出]\n");
        prompt.append("   题目：[具体题目内容]\n");
        prompt.append("   学生答案：[学生的答案]\n");
        prompt.append("   正确答案：[正确的答案]\n");
        prompt.append("   错误原因：[分析错误原因]\n");
        prompt.append("   ---\n");
        prompt.append("   [如有多个错题，重复上述格式]\n\n");
        prompt.append("请确保评价客观、公正、具有建设性，并且必须在开头明确给出得分。对于错题，请提供具体的正确答案和详细的错误分析。请只分析图片中实际存在的题目，不要建议补充额外的题目。");
        
        return prompt.toString();
    }
    
    private Map<String, Object> parseAIResponse(String aiResponse) {
        Map<String, Object> result = new HashMap<>();
        
        // 简单的解析逻辑，可以根据需要进一步优化
        result.put("fullResponse", aiResponse);
        
        // 尝试提取分数
        String score = extractScore(aiResponse);
        int totalScore = 0;
        if (score != null) {
            try {
                totalScore = Integer.parseInt(score);
            } catch (NumberFormatException e) {
                totalScore = 0;
            }
        }
        result.put("totalScore", totalScore);
        
        // 提取各个部分
        result.put("overallComment", extractSection(aiResponse, "总体评价"));
        result.put("strengths", extractListSection(aiResponse, "优点"));
        result.put("weaknesses", extractListSection(aiResponse, "不足之处"));
        result.put("suggestions", extractListSection(aiResponse, "改进建议"));
        result.put("encouragement", extractSection(aiResponse, "鼓励话语"));
        
        // 解析错题分析
        List<Map<String, Object>> wrongQuestions = extractWrongQuestions(aiResponse);
        
        // 根据错题分析构建题目数据结构
        List<Map<String, Object>> fillInBlanks = new ArrayList<>();
        List<Map<String, Object>> calculations = new ArrayList<>();
        List<Map<String, Object>> computations = new ArrayList<>();
        
        int fillInBlanksScore = 0;
        int calculationsScore = 0;
        int computationsScore = 0;
        
        for (Map<String, Object> wrongQ : wrongQuestions) {
            String question = (String) wrongQ.get("question");
            String studentAnswer = (String) wrongQ.get("studentAnswer");
            String correctAnswer = (String) wrongQ.get("correctAnswer");
            String errorReason = (String) wrongQ.get("errorReason");
            
            // 根据题目内容判断题目类型
            if (question.contains("填空") || question.contains("_") || question.contains("（）")) {
                Map<String, Object> fillInBlank = new HashMap<>();
                fillInBlank.put("question", question);
                fillInBlank.put("studentAnswer", studentAnswer);
                fillInBlank.put("correctAnswer", correctAnswer);
                fillInBlank.put("isCorrect", false);
                fillInBlank.put("errorReason", errorReason);
                fillInBlanks.add(fillInBlank);
            } else if (question.contains("=") || question.contains("+") || question.contains("-") || 
                      question.contains("×") || question.contains("÷") || question.contains("*") || question.contains("/")) {
                Map<String, Object> calculation = new HashMap<>();
                calculation.put("expression", question);
                calculation.put("studentAnswer", studentAnswer);
                calculation.put("correctAnswer", correctAnswer);
                calculation.put("isCorrect", false);
                calculation.put("errorReason", errorReason);
                calculations.add(calculation);
            } else {
                Map<String, Object> computation = new HashMap<>();
                computation.put("problem", question);
                computation.put("studentAnswer", studentAnswer);
                computation.put("correctAnswer", correctAnswer);
                computation.put("isCorrect", false);
                computation.put("errorReason", errorReason);
                computations.add(computation);
            }
        }
        
        result.put("fillInBlanks", fillInBlanks);
        result.put("calculations", calculations);
        result.put("computations", computations);
        result.put("fillInBlanksScore", fillInBlanksScore);
        result.put("calculationsScore", calculationsScore);
        result.put("computationsScore", computationsScore);
        
        return result;
    }
    
    private String extractScore(String text) {
        // 改进的分数提取逻辑
        String[] lines = text.split("\n");
        for (String line : lines) {
            if (line.contains("得分") || line.contains("分数")) {
                // 提取数字
                String[] parts = line.split("：");
                if (parts.length > 1) {
                    String scorePart = parts[1].trim();
                    
                    // 处理不同的分数格式
                    // 格式1: "65/100" -> 提取65
                    if (scorePart.contains("/")) {
                        String[] scoreParts = scorePart.split("/");
                        if (scoreParts.length > 0) {
                            String score = scoreParts[0].replaceAll("[^0-9]", "");
                            if (!score.isEmpty()) {
                                return score;
                            }
                        }
                    }
                    // 格式2: "65分" -> 提取65
                    else if (scorePart.contains("分")) {
                        String score = scorePart.replace("分", "").replaceAll("[^0-9]", "");
                        if (!score.isEmpty()) {
                            return score;
                        }
                    }
                    // 格式3: 纯数字 "65" -> 直接提取
                    else {
                        String score = scorePart.replaceAll("[^0-9]", "");
                        if (!score.isEmpty()) {
                            return score;
                        }
                    }
                }
            }
        }
        return null;
    }
    
    private String extractSection(String text, String sectionName) {
        String[] lines = text.split("\n");
        for (int i = 0; i < lines.length; i++) {
            if (lines[i].contains(sectionName)) {
                String[] parts = lines[i].split("：");
                if (parts.length > 1) {
                    return parts[1].trim();
                }
            }
        }
        return null;
    }
    
    private List<String> extractListSection(String text, String sectionName) {
        List<String> items = new ArrayList<>();
        String[] lines = text.split("\n");
        boolean inSection = false;
        
        for (int i = 0; i < lines.length; i++) {
            String line = lines[i].trim();
            
            if (line.contains(sectionName + "：")) {
                inSection = true;
                // 检查是否在同一行有内容
                String[] parts = line.split("：");
                if (parts.length > 1 && !parts[1].trim().isEmpty()) {
                    items.add(parts[1].trim());
                }
                continue;
            }
            
            if (inSection) {
                // 如果遇到下一个编号（如"4."），停止解析当前部分
                if (line.matches("^\\d+\\..*")) {
                    break;
                }
                
                // 解析以"-"开头的列表项
                if (line.startsWith("-") && line.length() > 1) {
                    items.add(line.substring(1).trim());
                } else if (!line.isEmpty() && !line.startsWith("   ")) {
                    // 如果不是空行且不是缩进行，可能是列表项
                    items.add(line);
                }
            }
        }
        
        return items;
    }
    
    private List<Map<String, Object>> extractWrongQuestions(String text) {
        List<Map<String, Object>> wrongQuestions = new ArrayList<>();
        String[] lines = text.split("\n");
        boolean inErrorSection = false;
        
        Map<String, Object> currentQuestion = null;
        
        for (String line : lines) {
            line = line.trim();
            
            if (line.contains("错题分析：")) {
                inErrorSection = true;
                continue;
            }
            
            if (inErrorSection) {
                if (line.startsWith("题目：")) {
                    // 保存上一个题目
                    if (currentQuestion != null && currentQuestion.get("question") != null) {
                        wrongQuestions.add(currentQuestion);
                    }
                    // 开始新题目
                    currentQuestion = new HashMap<>();
                    currentQuestion.put("question", line.substring(3).trim());
                } else if (line.startsWith("学生答案：") && currentQuestion != null) {
                    currentQuestion.put("studentAnswer", line.substring(5).trim());
                } else if (line.startsWith("正确答案：") && currentQuestion != null) {
                    currentQuestion.put("correctAnswer", line.substring(5).trim());
                } else if (line.startsWith("错误原因：") && currentQuestion != null) {
                    currentQuestion.put("errorReason", line.substring(5).trim());
                } else if (line.equals("---")) {
                    // 题目分隔符，保存当前题目
                    if (currentQuestion != null && currentQuestion.get("question") != null) {
                        wrongQuestions.add(currentQuestion);
                        currentQuestion = null;
                    }
                }
            }
        }
        
        // 保存最后一个题目
        if (currentQuestion != null && currentQuestion.get("question") != null) {
            wrongQuestions.add(currentQuestion);
        }
        
        return wrongQuestions;
    }
    

}